//
//  GXYJDViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/10/28.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "GXYJDViewController.h"

#import "YJDCell.h"
#import "GXYJDDetViewController.h"
@interface GXYJDViewController ()<UITableViewDelegate,UITableViewDataSource>{
    UIImageView *imageView;
    UILabel *labTit;
    NSInteger pageNo;
    NSMutableArray *datas;
}

@property (nonatomic,strong)UITableView *tableView;

@property (nonatomic,strong)NSMutableArray *array;

@end

@implementation GXYJDViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    _array = [NSMutableArray array];
    datas = [NSMutableArray array];
    [self showNav:@"已接单"];
    pageNo = 1;
    //[self loadData];
    
    [self loadUI];
    [self loadRefresh];
    
}

- (void)loadUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"available"]];
    imageView.hidden = YES;
    [self.view addSubview:imageView];
    [imageView makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.centerY.equalTo(self.view.centerY);
    }];
    
    labTit = [[UILabel alloc] init];
    labTit.text = @"暂无数据...";
    labTit.hidden = YES;
    labTit.font = [UIFont systemFontOfSize:15.0];
    labTit.textColor = [UIColor lightGrayColor];
    [self.view addSubview:labTit];
    [labTit makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.centerX);
        make.top.equalTo(imageView.bottom).offset(8);
    }];
    
    
}

//刷新控件
- (void)loadRefresh{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    //
    [self.tableView.mj_header beginRefreshing];
    //根据位置设置半透明
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    //上拉加载更多
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
}
//干洗已接单
- (void)loadData{
    [_tableView.mj_footer endRefreshing];
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setValue:_merid forKey:@"merchantid"];
    [parmas setValue:@"1" forKey:@"p"];
    NSLog(@"parmas:%@",parmas);
    
    NSString *url = [NSString stringWithFormat:@"%@/App/Ordermanage/yjcleaningorder",urlHead];
    NSLog(@"url:%@",url);
    [[AFHTTPSessionManager manager] GET:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"干洗已接单res:%@",responseObject);
        NSString *error = [responseObject objectForKey:@"error"];
        NSString *mssage = [responseObject objectForKey:@"mssage"];
        NSMutableArray *result = [responseObject objectForKey:@"result"];
        if ([error integerValue] == 200 && [result isKindOfClass:[NSArray class]]) {
            datas = [responseObject objectForKey:@"result"];
            _array = [datas mutableCopy];
            
            [self.tableView reloadData];
            _tableView.hidden = NO;
            imageView.hidden = YES;
            labTit.hidden = YES;
        }else{
            _tableView.hidden = YES;
            imageView.hidden = NO;
            labTit.hidden = NO;
            
        }
        [LICGToast showWithText:mssage];
        [_tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [_tableView.mj_header endRefreshing];
    }];
}

- (void)loadMoreData{
    [_tableView.mj_header endRefreshing];
    pageNo++;
    NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
    [parmas setObject:_merid forKey:@"merchantid"];
    NSString *p = [NSString stringWithFormat:@"%li",pageNo];
    [parmas setObject:p forKey:@"p"];
    NSLog(@"parmas:%@",parmas);
    NSString *url = [NSString stringWithFormat:@"%@/App/Ordermanage/yjcleaningorder",urlHead];
    [[AFHTTPSessionManager manager] GET:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"干洗已接单res:%@",responseObject);
        NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
        NSArray *arr = [responseObject objectForKey:@"result"];
        
        if (arr.count != 0) {
            datas = [arr mutableCopy];
            [_array addObjectsFromArray:datas];
            
            [_tableView reloadData];
        }
        
        
        [_tableView.mj_footer endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
        [_tableView.mj_footer endRefreshing];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    YJDCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"YJDCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.btnjd.layer.cornerRadius = 5.0;
    cell.btnjd.layer.borderColor = [UIColor redColor].CGColor;
    cell.btnjd.layer.borderWidth = 1.0;
    
    NSDictionary *itemDic = [_array objectAtIndex:indexPath.row];
    [cell.labDDH setText:[NSString stringWithFormat:@"订单号：%@",[itemDic objectForKey:@"ordernumber"]]];
    
    NSArray *arr = [itemDic objectForKey:@"details"];
    NSMutableArray *titles = [NSMutableArray array];
    CGFloat a = 0;
    NSInteger b = 0;
    for (NSDictionary *dic in arr) {
        NSString *name = [dic objectForKey:@"productname"];
        NSString *quantity = [NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"quantity"] floatValue]];
        NSString *unitprice = [NSString stringWithFormat:@"%.2f",[[dic objectForKey:@"unitprice"] floatValue]];
        a += [quantity floatValue] * [unitprice floatValue];
        [titles addObject:name];
        b += [quantity integerValue];
        
    }
    
    NSString *tit = [titles componentsJoinedByString:@","];
    cell.labSth.text = tit;
    cell.labPrice.text = [NSString stringWithFormat:@"%.2f元",a];
    cell.labNum.text = [NSString stringWithFormat:@"数量:x%li",b];
    
    [cell.labDate setText:[self getNewDate:[itemDic objectForKey:@"addtime"]]];
    
    NSString *ordeId = [NSString stringWithFormat:@"%li",[[itemDic objectForKey:@"id"] integerValue]];
    
    NSString *orderstate = [NSString stringWithFormat:@"%li",[[itemDic objectForKey:@"orderstate"] integerValue]];
    //4等骑手接单5取件中6运输中7正在洗衣8洗衣完成9等待骑手接单10取件中11配送中12配送完成13商家确定完成 20、骑手已送达
    if ([orderstate integerValue] == 4) {
        cell.labState.text = @"等待骑手接单";
        [cell.btnjd setTitle:@"取消" forState:UIControlStateNormal];
        
    }else if ([orderstate integerValue] == 5){
        cell.labState.text = @"等待骑手取件";
        [cell.btnjd setTitle:@"取消" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 6){
        cell.labState.text = @"等待骑手送达";
        [cell.btnjd setTitle:@"取消" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 20){
        cell.labState.text = @"骑手已送达";
        [cell.btnjd setTitle:@"开始洗衣" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 7){
        cell.labState.text = @"正在洗衣";
        [cell.btnjd setTitle:@"洗衣完成" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 8){
        cell.labState.text = @"等待骑手接单";
    }else if ([orderstate integerValue] == 9){
        cell.labState.text = @"等待骑手取件";
    }else if ([orderstate integerValue] == 10){
        cell.labState.text = @"骑手配送中";
    }else if ([orderstate integerValue] == 11){
        cell.labState.text = @"骑手配送完成";
        [cell.btnjd setTitle:@"确认完成" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 12){
        cell.labState.text = @"骑手配送完成";
        [cell.btnjd setTitle:@"确认完成" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 16){
        cell.labState.text = @"重新呼叫骑手";
        [cell.btnjd setTitle:@"确认呼叫" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 18){
        cell.labState.text = @"订单取消中";
        [cell.btnjd setTitle:@"确认取消" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 19){
        cell.labState.text = @"订单已取消";
        [cell.btnjd setTitle:@"确认取消" forState:UIControlStateNormal];
    }else if ([orderstate integerValue] == 21){
        cell.labState.text = @"等待商家自取";
        [cell.btnjd setTitle:@"确认完成" forState:UIControlStateNormal];
    }
    
    
    
//    cell.right = ^{
//        [self alerts:ordeId Price:price];
//    };
    
    return cell;
}

- (void)alerts:(NSString *)strid  Price:(NSString *)price{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"接单" message:@"该订单是否完成" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setObject:strid forKey:@"id"];//订单id
        NSString *url = [NSString stringWithFormat:@"%@/App/Ordermanage/affirmhousekeeping",urlHead];
        [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
            NSLog(@"res:%@",responseObject);
            NSString *error = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"error"] integerValue]];
            if ([error integerValue] == 200) {
                [_tableView.mj_header beginRefreshing];
            }
            
            [LICGToast showWithText:[responseObject objectForKey:@"mssage"]];
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [self presentViewController:alert animated:YES completion:nil];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130.0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dic = _array[indexPath.row];
    NSString *orderid = [NSString stringWithFormat:@"%li",[[dic objectForKey:@"id"] integerValue]];
    GXYJDDetViewController *det = [[GXYJDDetViewController alloc] init];
    det.orderId = orderid;
    det.merid = _merid;
    [self.navigationController pushViewController:det animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
